package spring.cloud.study.service;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import spring.cloud.study.entity.base.ResponseModel;

@Service
public class OrderService {
	private static final Logger logger = LoggerFactory.getLogger(OrderService.class);

	@Autowired
	private RestTemplate restTemplate;

	private String getGoodId() {
		return UUID.randomUUID().toString().replace("-", "");
	}

	public ResponseModel buy(int amount) {
		// 组装参数
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("goodId", getGoodId());
		params.put("amount", amount);
		// 远程调用
		ResponseModel res = restTemplate.getForObject("http://pay-server/pay/payment/{goodId}/{amount}",
				ResponseModel.class, params);
		return res;
	}


	public ResponseModel buyTimeOut(int amount) {
		long start = System.currentTimeMillis();
		// 组装参数
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("goodId", getGoodId());
		params.put("amount", amount);
		// 远程调用
		ResponseModel res = restTemplate.getForObject("http://pay-server/pay/payment/timeout/{goodId}/{amount}",
				ResponseModel.class, params);
		long end = System.currentTimeMillis();
		logger.info("[OrderService][buyTimeOut] runtime:" + (end-start));
		return res;
	}


}
